package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.DetailTabScriptDTO;
import com.xbongbong.paas.pojo.vo.DetailTabScriptVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.service.SaasDetailTabService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2019-11-20 15:24
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/detail/tab")
public class SaasDetailTabScriptController {
	@Resource
	private ProBaseConfig proBaseConfig;
	@Resource
	private SaasDetailTabService saasDetailTabService;
	
	@RequestMapping(value = "/byType", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String scriptTab(@RequestBody @Valid DetailTabScriptDTO detailTabScriptDTO, BindingResult br) throws XbbException {
		XbbResponse<DetailTabScriptVO> response;
		if ( br.hasErrors() ) {
			String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
			response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
		} else {
			try {
				if ( !proBaseConfig.getXbbCode().equals(detailTabScriptDTO.getXbbCode()) ) {
					throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
				}
				DetailTabScriptVO detailTabScriptVO = saasDetailTabService.scriptTab(detailTabScriptDTO);
				response = new XbbResponse<>(detailTabScriptVO);
			} catch (XbbException e) {
				response = new XbbResponse<>(e);
			}
		}
		return JSON.toJSONString(response);
	}
}
